package com.controller;

import com.model.UserModel;
import com.services.IUserServices;
import com.services.impl.UserServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: exam
 * @ClassName: CheckPwdServletController
 * @Description: 更改密码时，输入旧密码，检查密码是否正确
 * @Author: li
 * @Create: 2019-07-23 14:19
 */
@WebServlet("/CheckPwdServlet")
public class CheckPwdServletController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            String email = request.getParameter("email");
            String oldPwd = request.getParameter("oldPwd");
            
            if (email == null || oldPwd == null) {
                result.put("code", 400);
                result.put("msg", "参数错误");
                result.put("data", false);
                response.getWriter().write(JSONObject.fromObject(result).toString());
                return;
            }

            UserModel userModel = new UserModel();
            userModel.setEmail(email);
            userModel.setPwd(oldPwd);
            
            IUserServices services = new UserServicesImpl();
            boolean isValid = services.queryPwdByEmail(userModel);
            
            result.put("code", 0);
            result.put("msg", "验证成功");
            result.put("data", isValid);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "验证失败：" + e.getMessage());
            result.put("data", false);
        }
        
        response.getWriter().write(JSONObject.fromObject(result).toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
